package com.cloudpivot.receivales.excel.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.cloudpivot.receivales.excel.domain.ImportExcelDTO;
import com.cloudpivot.receivales.excel.entity.SalePlanEntity;
import com.cloudpivot.receivales.excel.entity.SalePlanPersonEntity;
import com.cloudpivot.receivales.excel.repository.SalePlanCalPersonEntityRepository;
import com.cloudpivot.receivales.excel.repository.SalePlanCalRepository;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 跟进信息的excel处理
 */

@Service
@Slf4j
public class SalePlanExcelServiceImpl {

    @Autowired
    private SalePlanCalRepository salePlanCalRepository;

    @Autowired
    private SalePlanCalPersonEntityRepository salePlanCalPersonEntityRepository;

//     private String[] depGroup = {"营销二区/安徽省区"};
  private String[] depGroup = {"营销一区/北区","营销一区/西北省区","营销一区/产品推广部","营销一区/华北省区","营销二区/产品推广部","营销二区/安徽省区","营销二区/福建省区","营销二区/江苏省区","营销二区/山东省区","营销二区/上海二区","营销二区/浙江省区","营销二区/end","营销三区/产品推广部","营销三区/川渝省区","营销三区/湖南省区","营销三区/豫鄂省区","营销三区/云贵省区","营销中心/公卫部","营销中心/渠道拓展部"};

    public Map<String, List<ImportExcelDTO>> handleAllData(String startDate, String endDate) {
        Map<String, List<ImportExcelDTO>> result = new HashMap<>();
        String[] dateArg = generateDateArray(startDate, endDate);

        //获取所有记录
        List<SalePlanEntity> followList = salePlanCalRepository.getAllEntity();
        //获取人员信息
        List<SalePlanPersonEntity> personList = salePlanCalPersonEntityRepository.getAllPerson();
        log.info("取数完成");
        //确认X轴的信息
        Map<String, Integer> mapX = handlerCountPerson(personList);

        //增加时间循环
        for (String date : dateArg) {
            List<ImportExcelDTO> resultList = new ArrayList<>();
            //执行Y轴信息
            //循环执行X轴信息
            for (Map.Entry<String, Integer> entry : mapX.entrySet()) {
                ImportExcelDTO importExcelDTO = new ImportExcelDTO();
                //部门名称
                String deptName = entry.getKey();
                importExcelDTO.setDeptName(deptName.replace("/end", "/二区"));
                importExcelDTO.setSumPerson(entry.getValue());
                //计算写数据 cal1
                Map<String, Integer> count1Map = cal1(followList, deptName, date);
                importExcelDTO.setFollowPerson(count1Map.get("count2"));
                importExcelDTO.setFollowCount(count1Map.get("count1"));
                importExcelDTO.setRelaCount(count1Map.get("count3"));
                importExcelDTO.setRelaCal(count1Map.get("count4"));
                resultList.add(importExcelDTO);
            }
            result.put(date, resultList);
        }
        log.info("临时打印结果====>>>>{}", JSONObject.toJSONString(result));
        return result;
    }

    /**
     * 计算写记录的人数
     *
     * @param followList
     * @param deptName
     * @param date
     * @return
     */
    private Map<String, Integer> cal1(List<SalePlanEntity> followList, String deptName, String date) {
        //填写人数
        int count2 = 0;
        //填写数量(有效的 followTime和createTime差2天之内)
        int count1 = 0;
        //关联项目的数量
        int count3 = 0;

        Map<String, Integer> count2Map = new HashMap<>();
        for (SalePlanEntity follow : followList) {
            String _deptName = follow.getDept();
            String _createTime = follow.getCreateTime();
            String _followTime = follow.getFollowTime();
            String creater = follow.getCreater();
            String targetType = follow.getTargetType(); //项目
            String keyId = follow.getKeyInitiative();
            if (_deptName.contains(deptName) && compareDate(_followTime, date,follow) == 0  && compareDate(_createTime, _followTime,follow) < 2) {
                count2Map.put(creater, 0);
                count1++;
                if (StringUtils.isNotBlank(keyId)) {
                    //需要记录到已关联的数量
                    count3++;
                }
                log.info("符合的记录打印===>{}",JSONObject.toJSON( follow));
            }
        }

        //整理数量(人数)
        for (Map.Entry<String, Integer> entry : count2Map.entrySet()) {
            count2++;
        }
        Map<String, Integer> result = new HashMap<>();
        result.put("count1", count1);
        result.put("count2", count2);
        result.put("count3", count3);

        // 增加count3除以count1的百分比（避免除零异常）
        if (count1 != 0) {
            int percentage = (count3 * 100) / count1;
            result.put("count4", percentage);
        } else {
            result.put("count4", 0);
        }
        return result;
    }

    /**
     * 返回 部门所有人数的map
     *
     * @return
     */
    private Map<String, Integer> handlerCountPerson(List<SalePlanPersonEntity> personList) {
        //转map
        Map<String, Integer> deptGroupMap = new HashMap<>();

        for (SalePlanPersonEntity person : personList) {
            String deptName = person.getDeptName();
            for (String _groupName : depGroup) {
                if (deptName.contains(_groupName)) {
                    //需要统计这个部门
                    if (deptGroupMap.containsKey(_groupName)) {
                        deptGroupMap.put(_groupName, deptGroupMap.get(_groupName) + 1);
                    } else {
                        deptGroupMap.put(_groupName, 1);
                    }
                }
            }
        }

        return deptGroupMap;
    }

    /**
     * 根据开始日期和结束日期生成日期数组
     *
     * @param startDate 开始日期 (格式: yyyy-MM-dd)
     * @param endDate 结束日期 (格式: yyyy-MM-dd)
     * @return 包含开始日期和结束日期以及中间所有日期的数组
     */
    private String[] generateDateArray(String startDate, String endDate) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate start = LocalDate.parse(startDate, formatter);
        LocalDate end = LocalDate.parse(endDate, formatter);
        
        List<String> dateList = new ArrayList<>();
        LocalDate currentDate = start;
        
        while (!currentDate.isAfter(end)) {
            dateList.add(currentDate.format(formatter));
            currentDate = currentDate.plusDays(1);
        }
        
        return dateList.toArray(new String[0]);
    }

    private long compareDate(String date1, String date2,SalePlanEntity follow ) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        long result=0L;

        if(follow.getId().equals("2f5fb6809e1e44df8ebeaecffd489591")){
            log.info("打印下记录=====>>>>>>>{}", JSONObject.toJSONString(follow));
        }

        try{
            LocalDate _date1 = LocalDate.parse(date1, formatter);
            LocalDate _date2 = LocalDate.parse(date2, formatter);
            result = ChronoUnit.DAYS.between(_date2,_date1 );

//            int result = _date1.compareTo(_date2);
            return result;
        }catch (Exception e){
            log.info("日期转换异常,打印异常记录===>{}", JSONObject.toJSONString(follow));
            return 0L;
        }
    }


}
